<?php

class Catalogue
{

    var $DB_obj = null;
    var $meccano = null;
    var $params      = array();
    var $error       = false;
    var $limit = 0;


    function Catalogue($DB = null, $MECCANO = null)
    {
        if(is_object($DB))
        {
            $this->DB_obj = &$DB;
        } else
        {
            $this->error['system'][] = "No DateBase Object registered!";
        }

        if(is_object($MECCANO))
        {
            $this->meccano = &$MECCANO;
        } else
        {
            $this->error['system'][] = "No MECCANO Object registered!";
        }

        $this->SetParams();
    }


    function Add($vars)
    {
        if(!is_array($vars))
        {
            $this->error[] = 'There is nothing to add!';
            return false;
        }

        @isDigit($vars['cat']);
        if($vars['cat'] == false || $vars['title'] == '')
        {
            if($vars['cat'] == false) $this->error[] = "There no Category selected!";
            if($vars['title'] == '') $this->error[] = "There no Title inputed!";
            if($vars['login'] == '') $this->error[] = "There no Login inputed!";
            if($vars['pwd'] == '') $this->error[] = "There no Password inputed!";
            return false;
        }

        isUrl($vars['webaddress']);
        isEmail($vars['e_mail']);

        $this->DB_obj->DB_QueryBuilder("INSERT INTO meccano_produce (title, login, pwd, cat, phones, description, img, address, webaddress, e_mail, dat) VALUES ('%s', '%s', MD5('%s'), %i, '%s', '%s', '%s', '%s', '%s', '%s', NOW());", array($vars['title'], $vars['login'], $vars['pwd'], $vars['cat'], $vars['phones'], $vars['description'], $vars['logo'], $vars['address'], $vars['webaddress'], $vars['e_mail']));

        return $this->DB_obj->DB_Query();
    }


    function Update($id, $vars)
    {
        @isDigit($id);
        if($id == false) return false;

        if(!is_array($vars))
        {
            $this->error[] = 'There is nothing to add!';
            return false;
        }

        @isDigit($vars['cat']);
        if($vars['cat'] == false || $vars['title'] == '')
        {
            if($vars['cat'] == false) $this->error[] = "There no Category selected!";
            if($vars['title'] == '') $this->error[] = "There no Title inputed!";
            if($vars['login'] == '') $this->error[] = "There no Login inputed!";
            return false;
        }
        isUrl($vars['webaddress']);
        isEmail($vars['e_mail']);

        if($vars['pwd'] != '')
        {
            $this->DB_obj->DB_QueryBuilder("UPDATE meccano_produce SET pwd = MD5('%s') WHERE id = %i", array($vars['pwd'], $id));
            $this->DB_obj->DB_Query();
        }

        $this->DB_obj->DB_QueryBuilder("UPDATE meccano_produce SET title = '%s', cat = %i, phones = '%s', description = '%s', img = '%s', address = '%s', webaddress = '%s', e_mail = '%s', dat = CURRENT_TIMESTAMP WHERE id = %i;", array($vars['title'], $vars['cat'], $vars['phones'], $vars['description'], $vars['logo'], $vars['address'], $vars['webaddress'], $vars['e_mail'], $id));

        $this->DB_obj->DB_Query();

        $result = $this->DB_obj->DB_Info();
        return $result['changed'];
    }


    /**
     * Get Category Entry
     *
     * @param integer $category
     * @param string $mode, can be: a - all, t - by title, d - by date, c - one per category, r - randomize
     * @return array
     */
    function Get($category = null, $mode = '')
    {
        $modes     = array('a','t','d','c','r');
        $sort      = ' ASC';
        $condition = '';
        $order     = '';
        $limit     = '';

        if(strlen($mode) > 1)
        {
            if(substr($mode, 1, 1) == '-') $sort = ' DESC';
        }

        $mode      = substr($mode, 0, 1);
        $mode      = in_array($mode, $modes) ? $mode : 'a';
        $list      = $this->_enclosureList($category);

        switch ($mode)
        {
            case 't':
                $order = " ORDER BY BINARY t1.title";
                break;

            case 'd':
                $order = " ORDER BY t1.dat";
                break;

            case 'c':
                if(count($list) > 1 || $list === false)
                {
                    $order = ' GROUP BY t1.cat ORDER BY RAND()';
                }
                break;

            case 'r':
                $order = " ORDER BY RAND()";
                break;

            case 'a':
            default:
                $order = " ORDER BY t1.cat";
        }

        $order = $order . $sort;

        if($this->limit > 0) $limit = ' LIMIT '.$this->limit;

        if($list != false) $condition = " AND t1.cat IN (" . implode(',', $list) . ")";

        $this->DB_obj->sql = "SELECT t1.*, t2.title AS category FROM meccano_produce AS t1, meccano_treetranslates AS t2 WHERE t1.cat = t2.id AND t2.lang = 'ru'". $condition . $order . $limit . ";";

        $this->DB_obj->DB_Fetch();

        if($this->DB_obj->rows > 0) return $this->DB_obj->fetched;

        return false;
    }


    function View($id)
    {
        isDigit($id);
        if($id == false) return false;

        $this->DB_obj->sql = "SELECT t1.*, t2.title AS category FROM meccano_produce AS t1, meccano_treetranslates AS t2 WHERE t1.cat = t2.id AND t2.lang = 'ru' AND t1.id = ".$id.";";

        $this->DB_obj->DB_Fetch();

        if($this->DB_obj->rows > 0) return $this->DB_obj->fetched;
        $this->limit = 0;

        return false;
    }

    /**
      * Delete entries from table
      *
      * @param integer|array $id
      * @return bool
      */
    function Delete($id)
    {
        if(is_array($id))
        {
            $del = array_filter($id, "isDigit");
        } else
        {
            isDigit($id);
            if($id != false) $del[] = $id;
        }
        unset($id);

        if(count($del) > 0)
        {
            $del = implode(',', $del);
            $this->DB_obj->sql = "DELETE FROM meccano_produce WHERE id IN (".$del.");";

            return $this->DB_obj->DB_Query();
        }

        return false;
    }

    function Search($str, $cat, $limit = 0, $length = 64)
    {
        $str = prepare_str($str);
        isDigit($cat, 'NOZERRO');
        isDigit($limit);
        isDigit($length);
        if($str == false) return false;
        if($length == false) $length = 64;
        $str = substr($str, 0, $length);
        $str = explode(" ", $str);
        $condition = array();

        if($cat != false)
        {
            $cat = ' AND t1.cat = '.$cat;
        } else
        {
            $cat = '';
        }

        foreach ($str as $value)
        {
            $condition[] = " t1.title LIKE '%".$value."%'";
            //$condition[] = " t1.description LIKE '%".$value."%'";
        }

        $condition = implode(' OR', $condition);

        $sql_limit = '';

        if($limit !== false || $limit != 0) $sql_limit = ' LIMIT 0,'.$limit;

        //$this->DB_obj->DB_QueryBuilder("SELECT *, (MATCH (partn) AGAINST ('%s' IN BOOLEAN MODE)*100) + (MATCH (title) AGAINST ('%s' IN BOOLEAN MODE)*50) + MATCH (description) AGAINST ('%s' IN BOOLEAN MODE) AS rating FROM  meccano_produce WHERE MATCH (partn,title,description) AGAINST ('%s' IN BOOLEAN MODE) ORDER BY rating DESC" . $sql_limit . ";", array($str, $str, $str, $str));
        //$this->DB_obj->sql = "SELECT * FROM meccano_produce WHERE ".$condition.$sql_limit;
        $this->DB_obj->sql = "SELECT t1.*, t2.title AS category FROM meccano_produce AS t1, meccano_treetranslates AS t2 WHERE (t1.cat = t2.id AND t2.lang = 'ru') AND (".$condition.")".$cat.$sql_limit;

        $this->DB_obj->DB_Fetch();

        if($this->DB_obj->rows > 0) return $this->DB_obj->fetched;

        return false;
    }


    function LastUpdate()
    {
        $this->DB_obj->sql = "SELECT dat FROM meccano_produce ORDER BY dat DESC LIMIT 1";
        $this->DB_obj->DB_Query();
        if($this->DB_obj->DB_GetRows() > 0)
        {
            return $this->DB_obj->DB_GetResult(0, 'dat');
        }

        return false;
    }


    /**
     * Just Count
     *
     * @param integer $category
     * @return integer
     */
    function Counter($category = '')
    {
        $condition = '';
        isDigit($category, 'NOZERRO');

        if($category != false)
        {
            $category = $this->meccano->ListOfID($category);
            $category = implode(',', $category);
            $condition = " WHERE cat IN (".$category.")";
        }
        $this->DB_obj->sql = "SELECT COUNT(*) AS counts FROM meccano_produce".$condition;
        $this->DB_obj->DB_Query();
        return $this->DB_obj->DB_GetResult(0, 'counts');
    }


    /**
     * Get Flat Tree with Counts Entry in each category
     *
     * @param unknown_type $category
     * @return unknown
     */
    function CountEntry($category = false)
    {
        $module = 'catalogue';
        $categories = null;

        isDigit($category, 'NOZERRO');
        $this->meccano->hide_root = true;
        $tree = $this->meccano->GetFlatList($category, $module);
        $this->meccano->hide_root = false;

        if(count($tree) > 0)
        {
            foreach ($tree as $value)
            {
                $categories[] = $value['id'];
            }

            $categories = implode(',', $categories);

            $this->DB_obj->sql = "SELECT cat, COUNT(*) AS counts FROM meccano_produce WHERE cat IN (".$categories.") GROUP BY cat;";
            $counts = $this->DB_obj->DB_Fetch();

            foreach ($counts as $value)
            {
                $var[$value['cat']] = $value['counts'];
            }

            for($i=0, $t=count($tree); $i<$t; $i++)
            {
                if(isset($var[$tree[$i]['id']]))
                {
                    $tree[$i]['counts'] = $var[$tree[$i]['id']];
                } else
                {
                    $tree[$i]['counts'] = 0;
                }
            }


            return $tree;
        }

        return false;
    }


    function _enclosureList($id, $depth = 0)
    {
        isDigit($id);
        isDigit($depth);
        if($id == false) return false;
        if($depth === false) $depth = 0;

        $this->meccano->demanded_depth = $depth;

        $tree = $this->meccano->GetFlatList($id);

        for ($i=0, $t=count($tree); $i<$t; $i++)
        {
            $list[$i] = $tree[$i]['id'];
        }

        $this->meccano->demanded_depth = 0;
        return $list;
    }

    function SetParams($params = 'clear')
    {
        if($params == 'clear')
        {
            $this->params['language'] = $this->meccano->system['lang'][0];
            return true;
        }

        $params = explode(';', $params);

        foreach ($params as $value)
        {
            $p = explode('=', $value);
            switch ($p[0])
            {
                case 'language':
                    strtolower($p[1]);
                    if(in_array($p[1], $this->meccano->system['lang'])) $this->params['language'] = $p[1];
                    break;
            }
        }
    }
}
?>